<template>
  <div class="proNum">
    <div class="reduce" @click="reduce">-</div>
    <input type="text" :value="value" @change="changeNum" />
    <div class="add" @click="add">+</div>
  </div>
</template>

<script>
import { Toast, Dialog } from 'vant'

export default {
  name: 'proNum',
  props: {
    value: {
      type: [Number, String],
      default: 1
    },
    mode: {
      type: String,
      default: 'add'
    }
  },
  methods: {
    add () {
      this.$emit('input', Number(this.value) + 1)
    },
    reduce () {
      if (this.value > 1) {
        this.$emit('input', Number(this.value) - 1)
      } else {
        if (this.mode === 'reduce') {
          Toast('至少选择一个商品')
        }
        if (this.mode === 'cart') {
          Dialog.confirm({
            title: '提示',
            message: '确定要删除该商品吗？',
            confirmButtonText: '确定删除',
            cancelButtonText: '再考虑一下'
          }).then(() => {
            this.$emit('input', 0)
          }).catch(() => {
          })
        }
      }
    },
    changeNum (e) {
      const val = e.target.value.trim()
      if (isNaN(val) || val <= 0) {
        this.$emit('input', 1)
        this.$toast('请输入正确的数量')
        return
      }
      this.$emit('input', val)
    }
  }

}

</script>

<style>
.proNum {
  display: flex;
  align-items: center;
  margin: 5px;
}
.reduce, .add {
  width: 30px;
  height: 30px;
  background-color: #f5f5f5;
  text-align: center;
  line-height: 30px;
  cursor: pointer;
}
input {
  width: 40px;
  margin: 0 5px;
  text-align: center;
}
</style>
